package work.mediway.mdm.biz.service.hierarchy.impl;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mediway.hos.app.base.seure.util.SecurityUtils;
import com.mediway.hos.common.utils.ExceptionUtil;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import work.mediway.mdm.core.page.QueryRequest;
import work.mediway.mdm.core.exception.DataException;
import work.mediway.mdm.core.transport.ErrorMsgVO;
import work.mediway.mdm.biz.entity.hierarchy.HosPerson;
import work.mediway.mdm.biz.mapper.hierarchy.HosPersonMapper;
import work.mediway.mdm.biz.service.common.CommonDictService;
import work.mediway.mdm.biz.service.hierarchy.HosPersonService;
import work.mediway.mdm.biz.util.MybatisPlusUtil;

@Slf4j
@Service
@RequiredArgsConstructor
public class HosPersonServiceImpl extends ServiceImpl<HosPersonMapper, HosPerson> implements HosPersonService {

    private final CommonDictService commonDictService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveHosPerson(HosPerson hosPerson) {
        MybatisPlusUtil.setCreateInfo(hosPerson, SecurityUtils.getLoginName());
        MybatisPlusUtil.setNullWhenBlank(hosPerson, HosPerson.CHECK_ATTR_ARRAY);
        this.save(hosPerson);
    }

    @Override
    public Page<HosPerson> findHosPerson(HosPerson hosPerson, QueryRequest queryRequest) {
        Page<HosPerson> page = new Page<>(queryRequest.getCurrent(), queryRequest.getSize());
        page.setRecords(this.baseMapper.find(page, hosPerson));
        return page;
    }

    @Override
    public Page<HosPerson> findHosPerson(String orgCode, QueryRequest queryRequest) {
        Page<HosPerson> page = new Page<>(queryRequest.getCurrent(), queryRequest.getSize());
        page.setRecords(this.baseMapper.findByOrg(page, orgCode));
        return page;
    }

    @Override
    public void updateHosPerson(HosPerson hosPerson) {
        String personID = hosPerson.getPaPersonID();
        if (StrUtil.isBlank(personID)) {
            throw new DataException("PA_PersonID不能为空");
        }
        if (ObjectUtil.isEmpty(this.baseMapper.findById(personID))) {
            throw new DataException(StrUtil.format("【PA_PersonID = {}】不存在", personID));
        }
        MybatisPlusUtil.setUpdateInfo(hosPerson, SecurityUtils.getLoginName());
        MybatisPlusUtil.setNullWhenBlank(hosPerson, HosPerson.CHECK_ATTR_ARRAY);
        this.updateById(hosPerson);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ErrorMsgVO deleteHosPerson(String personId) {
        ErrorMsgVO error = new ErrorMsgVO();
        String[] ids = StrUtil.splitToArray(personId, StringPool.COMMA);
        for (String id : ids) {
            try {
                //TODO: 删除关联
                this.removeById(id);
            } catch (Exception e) {
                log.error(ExceptionUtil.getExceptionMessage(e), e);
                error.setErrorMsg(id, StrUtil.format("人员【PA_PersonID = {}】删除失败, 失败原因【{}】", id, e.getMessage()));
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        error.setCount(ids.length);
        log.info("删除结果: {}", error);
        return error;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ErrorMsgVO importHosPerson(List<HosPerson> hosPersonList, boolean updateSupport) {
        ErrorMsgVO error = new ErrorMsgVO();
        if (CollUtil.isEmpty(hosPersonList)) {
            throw new DataException("导入人员数据不能为空！");
        }
        for (HosPerson person : hosPersonList) {
            try {
                HosPerson byId = this.baseMapper.findById(person.getPaPersonID());
                if (ObjectUtil.isEmpty(byId)) {
                    MybatisPlusUtil.setCreateInfo(person, SecurityUtils.getLoginName());
                    this.save(person);
                } else if (updateSupport) {
                    MybatisPlusUtil.setUpdateInfo(person, SecurityUtils.getLoginName());
                    MybatisPlusUtil.setNullWhenBlank(person, HosPerson.CHECK_ATTR_ARRAY);
                    this.updateById(person);
                } else {
                    error.setErrorMsg(person, StrUtil.format("人员【PA_PersonID = {}】已存在", person.getPaPersonID()));
                }
            } catch (Exception e) {
                log.error(ExceptionUtil.getExceptionMessage(e), e);
                error.setErrorMsg(person, StrUtil.format("人员【PA_PersonID = {}】导入失败, 失败原因【{}】", person.getPaPersonID(), e.getMessage()));
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        error.setCount(hosPersonList.size());
        return error;
    }
}
